//! # 配置构建器实现
//! 
//! 本模块提供了针对特定配置类型的构建器实现。

use crate::config::*;
use crate::builder::traits::*;
use rustcloud_core::{ServiceResult, ServiceError};

/// 服务配置构建器
pub struct ServiceConfigBuilder {
    config: ServiceConfig,
}

impl ServiceConfigBuilder {
    pub fn new(name: &str) -> Self {
        Self {
            config: ServiceConfig {
                name: name.to_string(),
                ..Default::default()
            },
        }
    }

    pub fn version(mut self, version: &str) -> Self {
        self.config.version = version.to_string();
        self
    }

    pub fn environment(mut self, env: &str) -> Self {
        self.config.environment = env.to_string();
        self
    }

    pub fn instance_id(mut self, id: &str) -> Self {
        self.config.instance_id = Some(id.to_string());
        self
    }

    pub fn description(mut self, desc: &str) -> Self {
        self.config.description = Some(desc.to_string());
        self
    }

    pub fn tag(mut self, key: &str, value: &str) -> Self {
        self.config.tags.insert(key.to_string(), value.to_string());
        self
    }
}

#[async_trait::async_trait]
impl ConfigurationBuilder<ServiceConfig> for ServiceConfigBuilder {
    fn build(self) -> ServiceResult<ServiceConfig> {
        if self.config.name.is_empty() {
            return Err(ServiceError::ConfigError("服务名称不能为空".to_string()));
        }
        Ok(self.config)
    }
}

/// 网络配置构建器
pub struct NetworkConfigBuilder {
    config: NetworkConfig,
}

impl NetworkConfigBuilder {
    pub fn new() -> Self {
        Self {
            config: NetworkConfig::default(),
        }
    }

    pub fn port(mut self, port: u16) -> Self {
        self.config.port = port;
        self
    }

    pub fn health_port(mut self, port: u16) -> Self {
        self.config.health_port = port;
        self
    }

    pub fn admin_port(mut self, port: u16) -> Self {
        self.config.admin_port = Some(port);
        self
    }

    pub fn bind_address(mut self, address: &str) -> Self {
        self.config.bind_address = address.to_string();
        self
    }

    pub fn tls(mut self, cert_file: &str, key_file: &str) -> Self {
        self.config.tls = Some(TlsConfig {
            enabled: true,
            cert_file: cert_file.to_string(),
            key_file: key_file.to_string(),
            ca_file: None,
        });
        self
    }
}

#[async_trait::async_trait]
impl ConfigurationBuilder<NetworkConfig> for NetworkConfigBuilder {
    fn build(self) -> ServiceResult<NetworkConfig> {
        if self.config.port == 0 {
            return Err(ServiceError::ConfigError("服务端口不能为0".to_string()));
        }
        Ok(self.config)
    }
}